package com.tencent.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tencent.basic.exception.BusinessException;
import com.tencent.basic.jwt.JwtUtils;
import com.tencent.basic.jwt.LoginData;
import com.tencent.basic.jwt.RsaUtils;
import com.tencent.basic.service.serviceimpl.BaseServiceImpl;
import com.tencent.basic.util.AjaxResult;
import com.tencent.basic.util.HttpUtil;
import com.tencent.basic.util.Md5Utils;
import com.tencent.basic.util.StrUtils;
import com.tencent.system.domain.Menu;
import com.tencent.system.mapper.MenuMapper;
import com.tencent.system.mapper.PermissionMapper;
import com.tencent.user.constant.WxConstants;
import com.tencent.user.domain.Logininfo;
import com.tencent.user.domain.User;
import com.tencent.user.dto.LoginDto;
import com.tencent.user.mapper.LogininfoMapper;
import com.tencent.user.mapper.UserMapper;
import com.tencent.user.service.ILogininfoService;
import com.tencent.wxUser.domain.Wxuser;
import com.tencent.wxUser.mapper.WxuserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void add(Logininfo logininfo) {
        super.add(logininfo);
    }

    @Override
    public void update(Logininfo logininfo) {
        super.update(logininfo);
    }

    @Override
    public void del(Long id) {
        super.del(id);
    }

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        // 通过account和type去查数据库
        Logininfo logininfo = logininfoMapper.accountLogin(loginDto);
        // 2.判断logininfo对象
        // 如果为空，则账号输错了
        if (logininfo == null){
            throw new BusinessException("账号错误");
        }else{
            // 将前端输入的密码MD5加盐
            String inputPwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            if (!inputPwd.equals(logininfo.getPassword())){
                throw new BusinessException("密码错误");
            }else{
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
//                String token = UUID.randomUUID().toString();
//                // 保存到redis中的值必须序列化
//                redisTemplate.opsForValue().set(token, logininfo ,30, TimeUnit.MINUTES);
//
//                // 将token信息对象村在MAp中
//                Map<String, Object> map = new HashMap<>();
//                map.put("token",token);
//                logininfo.setPassword(null);
//                logininfo.setSalt(null);
//                map.put("logininfo", logininfo);
                return map;
            }
        }
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String, Object> map = new HashMap<>();
        // 将登录信息放进map集合中
        map.put("logininfo", logininfo);
        // 封装成logininfo对象
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        // 如果登录的是管理员
        if (logininfo.getType() == 0) {
            // 1.如果是后台管理元，获取当前登陆人的所有菜单
            List<Menu> menus = menuMapper.getMenuByLogininfoId(logininfo.getId());
            // 2.如果是后台管理元，获取当前登陆人的所有权限
            List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
            loginData.setMenus(menus);
            loginData.setPermissions(permissions);
            map.put("menus", menus);
            map.put("permissions", permissions);
        }
            try {
                // 3.获取私钥
                PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
                // 4.通过私钥对LoginData对象加密
                String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);
                // 5.将loginingfo，菜单，权限，jwtToken，疯转到Map

                map.put("token", jwtToken);
            }catch (Exception e){
                e.printStackTrace();
            }

        return map;
    }



    @Override
    public AjaxResult wechatLogin(String code) {
        //1.准备请求和替换参数
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE",code);
        //2.使用HttpUtil发送请求
        String jsonStr = HttpUtil.httpGet(url);

        // 3.将json格式数据转为json对象获取token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        // 4.通过openid直接查询数据库
        Wxuser wxuser = wxuserMapper.findByOpenId(openid);

        // 4.1查询到了斌且user_id有值以前绑定过
        if(wxuser!=null && wxuser.getUserId()!=null){ //绑定了
            User user = userMapper.findById(wxuser.getUserId());
            if(user != null){
                //通过user对象的logininfoId查logininfo对象
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

                String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

                //将token和登录信息对象对存在Map ，然后返回
                Map<String, Object> map = new HashMap<>();
                map.put("token",token); //后续做登录拦截验证
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo); //让前端显示用户信息

                return AjaxResult.me().setResultObj(map);
            }
        }

        //4.2.如果没有= 没有绑定 = return false = 让前端去跳转到绑定页面
        // ?accessToken=xxxx&openId=yyy;
        String params = "?accessToken="+accessToken+"&openId="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //一：校验：空值校验 手机号码和验证码
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode) ){
            throw new BusinessException("信息不能为null");
        }

        //二：校验: 校验手机验证码是否过期  或 是否正确
        Object codeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if(codeObj==null){
            throw new BusinessException("手机验证码过期");
        }
        if(!codeObj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }


        //三：第三个请求并且替换数据，然后发送
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        //四：处理json字符串 - 微信用户信息 - 将json字符串转换一个Wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        //五：绑定流程 - phone绑定
        //1.通过phone去查t_user
        User user = userMapper.findByPhone(phone);
        //a.如果有，直接绑定 -  //用户最开始用手机注册了，后来又用微信扫码注册了
        if(user==null){
            //b.如果没有，应该通过phone创建一个User对象，下添加t_logininfo,在添加user对象
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.add(logininfo);//自增id
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);//自增id
        }
        //2.将user_id设置到Wxuser对象,保存到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);

        //3.免密登录，返回token和logininfo
        //通过user对象的logininfoId查logininfo对象
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //4.将token和登录信息对象对存在Map ，然后返回
        Map<String, Object> result = new HashMap<>();
        result.put("token",token); //后续做登录拦截验证
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        result.put("logininfo",logininfo); //让前端显示用户信息

        return AjaxResult.me().setResultObj(result);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(4);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String address = jsonObject.getString("country")
                +jsonObject.getString("province")+jsonObject.getString("city");
        wxuser.setAddress(address);
        return wxuser;
    }

}
